import {
  apiGetAddressList,
  apiUpdateAddress,
  apiAddAddress
} from "../../service/api/user";
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

let type = '';

Page({
  data: {
    addressList: [],
    addressEditShow: false,
    editingName: '',
    editingPhone: '',
    editingAddress: '',
    editingId: '',
  },

  // 订单选择地址
  chooseItem(e) {
    if (type == 'add') {
      const item = e.currentTarget.dataset.item;
      this.changeUserInfo(item);
      wx.navigateBack({
        delta: 1,
      })
    }
  },

  changeUserInfo(item) {
    //获取页面栈
    const pages = getCurrentPages();
    if (pages.length > 1) {
      //上一个页面实例对象 
      const prePage = pages[pages.length - 2];
      prePage.changeUserInfo(item)
    }
  },

  openEditAddressDialog(e) {
    const item = e.currentTarget.dataset.item;
    if (item?.id) {
      this.setData({
        editingId: item.id,
        editingName: item.name,
        editingPhone: item.phone,
        editingAddress: item.address,
        addressEditShow: true
      })
    } else {
      // 说明是新增地址
      this.setData({
        editingId: '',
        editingName: '',
        editingPhone: '',
        editingAddress: '',
        addressEditShow: true
      })
    }
  },

  fetchQquest() {
    const {
      editingName: name,
      editingPhone: phone,
      editingAddress: address
    } = this.data;
    if (!name || !phone || !address) {
      Toast('请输入完整');
      return;
    }
    if (this.data.editingId) {
      this.fetchUpdateAddress();
    } else {
      this.fetchAddAddress();
    }
  },

  fetchAddAddress() {
    const {
      editingName: name,
      editingPhone: phone,
      editingAddress: address
    } = this.data;
    apiAddAddress({
      name,
      phone,
      address
    }).then(res => {
      if (res?.data?.res) {
        Toast.success('添加成功');
      }
    })
  },

  fetchUpdateAddress() {
    const {
      editingId: id,
      editingName: name,
      editingPhone: phone,
      editingAddress: address
    } = this.data;
    apiUpdateAddress({
      id,
      name,
      phone,
      address
    }).then(res => {
      if (res?.data?.res) {
        Toast.success('修改成功');
      }
    })
  },

  onLoad: function (options) {
    type = options?.type;
    apiGetAddressList().then(res => {
      this.setData({
        addressList: res?.data
      })
    })
  },
})